<template>
  <div class="history-page">
    <el-row :gutter="20" class="summary-row">
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-icon primary">
            <el-icon><ChatLineRound /></el-icon>
          </div>
          <div class="summary-content">
            <p class="summary-label">问答记录</p>
            <p class="summary-value">{{ stats?.totalQuestionRecords ?? 0 }}</p>
            <p class="summary-sub" v-if="stats?.latestQuestionTime">
              最近：{{ formatTime(stats.latestQuestionTime) }}
            </p>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-icon warning">
            <el-icon><PictureRounded /></el-icon>
          </div>
          <div class="summary-content">
            <p class="summary-label">影像分析</p>
            <p class="summary-value">{{ stats?.totalImageRecords ?? 0 }}</p>
            <p class="summary-sub" v-if="stats?.latestImageTime">
              最近：{{ formatTime(stats.latestImageTime) }}
            </p>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="12" :md="24" :sm="24" :xs="24">
        <el-card shadow="hover" class="summary-card intro-card">
          <div>
            <h3>健康档案中心</h3>
            <p>
              追踪您的提问与影像分析记录，支持按类型筛选，辅助医生快速了解您的健康轨迹。
            </p>
          </div>
          <el-button type="primary" link @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="history-card">
      <template #header>
        <div class="history-header">
          <div class="history-left">
            <h3>记录时间线</h3>
            <p>按时间倒序展示，便于快速回顾</p>
          </div>
          <div class="history-actions">
            <el-select v-model="filters.type" placeholder="全部类型" clearable size="small" @change="loadHistory">
              <el-option label="全部类型" :value="undefined" />
              <el-option label="问答记录" value="QUESTION" />
              <el-option label="影像分析" value="IMAGE" />
            </el-select>
            <el-button size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-empty v-if="!loading && items.length === 0" description="暂无历史记录" />
      <el-skeleton v-else :loading="loading" animated :rows="6">
        <el-timeline>
          <el-timeline-item
            v-for="item in items"
            :key="item.id + item.type"
            :timestamp="formatTime(item.timestamp)"
            placement="top"
          >
            <el-card shadow="hover" class="timeline-card">
              <div class="timeline-header">
                <div class="timeline-title">
                  <el-icon :class="['timeline-icon', iconClass(item.type)]">
                    <component :is="item.type === 'QUESTION' ? ChatLineRound : PictureRounded" />
                  </el-icon>
                  <div>
                    <h4>{{ item.title }}</h4>
                    <p>{{ item.summary }}</p>
                  </div>
                </div>
                <div class="timeline-tags">
                  <el-tag
                    v-for="tag in item.tags"
                    :key="tag"
                    size="small"
                    effect="dark"
                    :type="tagType(item.type)"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
              <el-divider />
              <div class="timeline-body">
                <div v-if="item.type === 'QUESTION'" class="body-grid">
                  <div class="body-field">
                    <label>问答分类</label>
                    <span>{{ metadataLabel(item.metadata.qaType as string) }}</span>
                  </div>
                  <div class="body-field">
                    <label>置信度</label>
                    <span>{{ formatConfidence(item.metadata.confidence as number) }}</span>
                  </div>
                </div>
                <div v-else class="body-grid">
                  <div class="body-field">
                    <label>分析类型</label>
                    <span>{{ analysisLabel(item.metadata.analysisType as string) }}</span>
                  </div>
                  <div class="body-field">
                    <label>置信度</label>
                    <span>{{ formatConfidence(item.metadata.confidence as number) }}</span>
                  </div>
                </div>
                <div v-if="item.type === 'IMAGE' && Array.isArray(item.metadata.suggestions)" class="body-suggestions">
                  <label>调理建议</label>
                  <ul>
                    <li v-for="suggestion in item.metadata.suggestions as string[]" :key="suggestion">
                      {{ suggestion }}
                    </li>
                  </ul>
                </div>
                <el-button
                  v-if="item.type === 'IMAGE' && item.metadata.previewUrl"
                  type="primary"
                  link
                  size="small"
                  @click="openPreview(item)"
                >
                  <el-icon><View /></el-icon>
                  查看原图
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-skeleton>

      <div class="pagination-wrapper" v-if="items.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="filters.size"
          :current-page="filters.page"
          :total="totalItems"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="previewDialog.visible" title="原图预览" width="720px" destroy-on-close>
      <div class="dialog-body">
        <img v-if="previewDialog.imageUrl" :src="previewDialog.imageUrl" alt="历史图片" />
        <el-empty v-else description="图片加载中..." />
      </div>
      <template #footer>
        <el-button @click="closePreview">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import dayjs from 'dayjs';
import { ChatLineRound, PictureRounded, Refresh, View } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { fetchHistory } from '@/api/history';
import type { HistoryItem, HistoryItemType, HistoryResponse, HistoryStats } from '@/types/history';
import { getImagePreview } from '@/api/images';

const items = ref<HistoryItem[]>([]);
const stats = ref<HistoryStats>();
const loading = ref(false);
const totalItems = ref(0);

const filters = reactive<{ type?: HistoryItemType; page: number; size: number }>({
  type: undefined,
  page: 1,
  size: 10,
});

const previewDialog = reactive<{ visible: boolean; imageUrl: string | null; recordId: string | null }>({
  visible: false,
  imageUrl: null,
  recordId: null,
});

const loadHistory = async () => {
  loading.value = true;
  try {
    const data = await fetchHistory({
      type: filters.type,
      page: filters.page,
      size: filters.size,
    });
    items.value = data.items;
    stats.value = data.stats;

    // Estimate total for pagination (simple heuristic based on stats)
    const total = (filters.type === 'QUESTION'
      ? data.stats?.totalQuestionRecords
      : filters.type === 'IMAGE'
      ? data.stats?.totalImageRecords
      : (data.stats?.totalQuestionRecords ?? 0) + (data.stats?.totalImageRecords ?? 0)) ?? 0;
    totalItems.value = total;
  } catch (error) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handleRefresh = () => {
  filters.page = 1;
  loadHistory();
};

const handlePageChange = (page: number) => {
  filters.page = page;
  loadHistory();
};

const formatTime = (time?: string) => (time ? dayjs(time).format('YYYY/MM/DD HH:mm') : '暂无');

const formatConfidence = (value?: number | string) => {
  if (value === undefined || value === null) {
    return 'N/A';
  }
  const numeric = typeof value === 'number' ? value : Number(value);
  if (Number.isNaN(numeric)) {
    return 'N/A';
  }
  return `${(numeric * 100).toFixed(0)}%`;
};

const iconClass = (type: HistoryItemType) => (type === 'QUESTION' ? 'primary' : 'warning');

const tagType = (type: HistoryItemType) => (type === 'QUESTION' ? 'success' : 'warning');

const analysisLabel = (value?: string) => {
  switch (value) {
    case 'TONGUE_DIAGNOSIS':
      return '舌诊分析';
    case 'WOUND_ASSESSMENT':
      return '创口识别';
    case 'SKIN_CONDITION':
      return '皮肤评估';
    default:
      return '影像分析';
  }
};

const metadataLabel = (value?: string) => {
  switch (value) {
    case 'TCM':
      return '中医问诊';
    case 'WESTERN':
      return '西医问诊';
    case 'HYBRID':
      return '中西结合';
    default:
      return '问答记录';
  }
};

const openPreview = async (item: HistoryItem) => {
  if (item.type !== 'IMAGE' || !item.metadata.previewUrl) {
    return;
  }
  previewDialog.visible = true;
  previewDialog.recordId = item.id;
  if (previewDialog.imageUrl) {
    URL.revokeObjectURL(previewDialog.imageUrl);
  }
  previewDialog.imageUrl = null;
  try {
    const response = await getImagePreview(item.id);
    const blob = new Blob([response], { type: 'image/jpeg' });
    previewDialog.imageUrl = URL.createObjectURL(blob);
  } catch (error) {
    ElMessage.error('图片载入失败，请稍后重试');
    previewDialog.visible = false;
  }
};

const closePreview = () => {
  if (previewDialog.imageUrl) {
    URL.revokeObjectURL(previewDialog.imageUrl);
  }
  previewDialog.visible = false;
  previewDialog.imageUrl = null;
  previewDialog.recordId = null;
};

watch(
  () => filters.type,
  () => {
    filters.page = 1;
    loadHistory();
  },
);

loadHistory();
</script>

<style scoped lang="scss">
.history-page {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.summary-row {
  .summary-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    border-radius: 16px;
  }
}

.summary-icon {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 26px;

  &.primary {
    background: rgba(59, 130, 246, 0.12);
    color: #2563eb;
  }

  &.warning {
    background: rgba(249, 115, 22, 0.12);
    color: #f97316;
  }
}

.summary-content {
  .summary-label {
    margin: 0;
    font-size: 0.9rem;
    color: #6b7280;
  }

  .summary-value {
    margin: 0.25rem 0 0;
    font-size: 1.8rem;
    font-weight: 600;
    color: #111827;
  }

  .summary-sub {
    margin: 0.25rem 0 0;
    font-size: 0.78rem;
    color: #9ca3af;
  }
}

.intro-card {
  justify-content: space-between;
  align-items: center;
}

.history-card {
  border-radius: 16px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .history-left {
    h3 {
      margin: 0;
      font-size: 1.15rem;
      font-weight: 600;
      color: #1f2937;
    }

    p {
      margin: 0.25rem 0 0;
      color: #6b7280;
      font-size: 0.9rem;
    }
  }

  .history-actions {
    display: flex;
    gap: 0.75rem;
    align-items: center;
  }
}

.timeline-card {
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
  padding-bottom: 0.5rem;

  h4 {
    margin: 0 0 0.25rem;
    font-size: 1.05rem;
    color: #1f2937;
  }

  p {
    margin: 0;
    color: #4b5563;
  }
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
}

.timeline-title {
  display: flex;
  gap: 0.75rem;
  align-items: flex-start;
}

.timeline-icon {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: rgba(59, 130, 246, 0.12);
  color: #2563eb;

  &.warning {
    background: rgba(249, 115, 22, 0.12);
    color: #f97316;
  }
}

.timeline-tags {
  display: inline-flex;
  gap: 0.5rem;
}

.timeline-body {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.body-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 1rem;
}

.body-field {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;

  label {
    font-size: 0.75rem;
    color: #9ca3af;
    letter-spacing: 0.08em;
  }

  span {
    color: #1f2937;
    font-weight: 500;
  }
}

.body-suggestions {
  label {
    display: block;
    font-size: 0.75rem;
    color: #9ca3af;
    letter-spacing: 0.08em;
    margin-bottom: 0.25rem;
  }

  ul {
    margin: 0;
    padding-left: 1.2rem;
    color: #374151;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 0.5rem 0 0.25rem;
}

.dialog-body {
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 70vh;

  img {
    max-width: 100%;
    max-height: 70vh;
    border-radius: 12px;
  }
}

@media screen and (max-width: 768px) {
  .summary-row {
    .summary-card {
      margin-bottom: 1rem;
    }
  }

  .history-actions {
    flex-direction: column;
    align-items: flex-end;
  }
}
</style>

